import { listNotRefer } from '@/services/workBench';
import {
  DownOutlined,
  LinkOutlined,
  MessageOutlined,
  SearchOutlined,
  UpOutlined,
} from '@ant-design/icons';
import { Empty, Input } from 'antd';
import moment from 'moment';
import React, { useCallback, useEffect, useState } from 'react';
import RelationModal from './RelationModal';
import styles from './index.less';

const ClassifySession: React.FC = ({}) => {
  const [visibleModal, setVisibleModal] = useState(false);
  const [relativeId, setRelativeId] = useState('');
  const [chatList, setChatList] = useState<any>([]);
  const [sortBy, setSortBy] = useState<boolean>(true); // true: 时间正序，false: 时间倒序
  const [timer, setTimer] = useState<any>(null);

  const init = async (value?: string) => {
    const params: any = {};
    if (sortBy) {
      params.createAtSort = 0;
    } else {
      params.createAtSort = 1;
    }
    if (value) {
      params.description = value;
    } else {
      params.description = '';
    }

    const { code, data } = await listNotRefer(params);
    if (code === 200 && data) {
      // 跟踪是否遇到 dayRange 为 1 的项
      let firstDayFlag = false;
      let secDayFlag = false;
      const arr = data.map((item: any) => {
        if (item.dayRange === 0 && !firstDayFlag) {
          firstDayFlag = true;
          return { ...item, dayNameSelf: '今天' }; // 添加 isfirstday 属性
        }
        if (item.dayRange === 1 && !secDayFlag) {
          secDayFlag = true;
          return { ...item, dayNameSelf: '昨天' }; // 添加 isfirstday 属性
        }
        return { ...item, isfirstday: null }; // 返回其他项不变
      });
      setChatList(arr);
      // setChatList(data);
    }
  };

  useEffect(() => {
    init();
  }, [sortBy]);

  const handleSearch = useCallback((value: any) => {
    init(value);
  }, []);

  const handleChange = (e: { target: { value: any } }) => {
    const value = e.target.value;
    // 清除之前的定时器（如果有的话）
    if (timer) {
      clearTimeout(timer);
    }
    // 设置新的定时器，延迟 2 秒触发搜索
    const newTimer = setTimeout(() => {
      handleSearch(value);
    }, 1000); // 延迟 2 秒
    // 更新定时器
    setTimer(newTimer);
  };

  return (
    <div className={styles['classify-session']}>
      <div className={`flex-between ${styles['header-wrap']}`}>
        <div />
        <div>
          <Input
            style={{ width: 600 }}
            size="middle"
            placeholder="模糊搜索"
            prefix={<SearchOutlined />}
            onChange={handleChange}
          />
        </div>
        <div
          className={`flex-between  ${styles['sort-time']}`}
          onClick={() => {
            setSortBy(!sortBy);
          }}
        >
          创建时间
          {sortBy ? (
            <DownOutlined style={{ marginLeft: 6, marginTop: 2 }} />
          ) : (
            <UpOutlined style={{ marginLeft: 6, marginTop: 2 }} />
          )}
        </div>
      </div>
      {chatList && chatList.length > 0 ? (
        chatList.map((item: any, index: number) => {
          return (
            <div className={styles['list-box']} key={index}>
              {/* <div className={styles['today-title']}>今天</div> */}
              {item?.dayNameSelf && (
                <div className={styles['today-title']}>{item?.dayNameSelf}</div>
              )}
              <div
                className={`flex-between  ${styles['list-item']}`}
                style={{ marginBottom: 16 }}
              >
                <div className={`flex-between  ${styles['left-item']}`}>
                  <div>
                    <MessageOutlined
                      style={{ color: '#dc2e00', marginRight: 8, fontSize: 16 }}
                    />
                    {item?.description}
                  </div>
                  <div style={{ color: '#6b7280' }}>
                    {moment(item?.createdAt).format('YYYY-MM-DD HH:mm')}
                  </div>
                </div>
                <div
                  className={`flex-between  ${styles['right-item']}`}
                  onClick={() => {
                    setRelativeId(item?.id);
                    setVisibleModal(true);
                    setTimeout(() => {
                      setVisibleModal(false);
                    });
                  }}
                >
                  <LinkOutlined />
                </div>
              </div>
            </div>
          );
        })
      ) : (
        <>
          <Empty style={{ marginTop: 100 }} />
        </>
      )}
      <RelationModal
        visibleModal={visibleModal}
        relativeId={relativeId}
        init={init}
      />
    </div>
  );
};

export default ClassifySession;
